package com.sdkx.wear_os.retrofit.response

import com.sdkx.wear_os.app.MyApplication
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import com.sdkx.wear_os.retrofit.ApiServiceUrl
import com.sdkx.wear_os.retrofit.api.ApiService
import com.sdkx.wear_os.retrofit.interceptor.InterceptorUtils
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import com.sdkx.wear_os.bean.Constant
import java.util.concurrent.TimeUnit


/**
 * object实现静态
 */
object RetrofitUtil {
    private var gson: Gson = GsonBuilder()
        .setLenient()
        .create()
    val retrofit: Retrofit = Retrofit.Builder()
        .baseUrl(ApiServiceUrl.BASE_URL)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .client(okHttpClient)
        .build()
    val apiService: ApiService = retrofit.create(ApiService::class.java)

    /**
     * 配置http
     */
    private val okHttpClient: OkHttpClient
        get() {
            var builder = OkHttpClient.Builder()
            builder = setHttpClientBuilder(builder)
            return builder.build()
        }

    private fun setHttpClientBuilder(builder: OkHttpClient.Builder): OkHttpClient.Builder {
        builder.apply {
            //设置缓存配置 缓存最大10M
//            cache(Cache(File(MyApplication.application.cacheDir, "uf_cache"), 10 * 1024 * 1024))
            //添加请求头
            addInterceptor(Interceptor {
                val appToken = MyApplication.fastKV.getString(Constant.APP_TOKEN)
                val request =
                    it.request().newBuilder().addHeader("appToken", appToken)
                        .build()
                return@Interceptor it.proceed(request)
            })
            //添加返回数据拦截器
            addInterceptor(InterceptorUtils.logInterceptor())
            //超时时间 连接、读、写
            connectTimeout(10, TimeUnit.SECONDS)
            readTimeout(30, TimeUnit.SECONDS)
            writeTimeout(30, TimeUnit.SECONDS)

        }
        return builder
    }

}